var app = getApp();
var Bmob = require("../../utils/bmob.js");
Page({
  data: {
    filterId: 1,
    searchWords: '',
    placeholder: '鲜花',
    servicelist: null
  },
  onLoad: function () {
    var self = this;
    //定位
  },
  onShow: function () {
    //this.setData({
    //	showResult: false
    //});
  },
  inputSearch: function (e) {
    this.setData({
      searchWords: e.detail.value
    });
  },
  doSearch: function () {
    this.getLikeSearchResultByKey(this.data.searchWords);
    this.setData({
      pageLoading: true
    });
  },
  tapFilter: function (e) {
    switch (e.target.dataset.id) {
      case '1':
        this.data.servicelist.sort(function (a, b) {
          return a.store_config - b.store_config;
        });
        break;
      case '2':
        this.data.servicelist.sort(function (a, b) {
          return b.createdAt - a.createdAt;
        });
        break;
      case '3':
        this.data.servicelist.sort(function (a, b) {
          return a.updatedAt - b.updatedAt;
        });
        break;
    }
    this.setData({
      filterId: e.target.dataset.id,
      servicelist: this.data.servicelist
    });
  },
  getLikeSearchResultByKey: function (key) { //Bmob模糊查询 数据量较小的时候使用
    let self = this;
    wx.showLoading();
    var businessNameQuery = Bmob.Query('Business');
    businessNameQuery.select("store_name");
    //businessQuery.equalTo("store_name", { "$regex": "" + this.data.searchWords + ".*" }); //收费的

    businessNameQuery.find().then(res => {
      var likeIdArray = [];
      for (var i = 0; i < res.length; i++) {
        if (res[i].store_name.toLowerCase().indexOf(key.toLowerCase()) >= 0) {
          likeIdArray.push(res[i].objectId);
        }
      }

      var businessQuery = Bmob.Query('Business');
      businessQuery.containedIn("objectId", likeIdArray);
      businessQuery.find().then(result =>{
          wx.hideLoading();
          self.setData({
            servicelist: result,
            showResult: true,
            pageLoading: false
          });
          console.log(self.data.servicelist);
      }).catch(error => {
        console.log(error);
        wx.hideLoading();
      });
    }).catch(error => {
      console.log(error);
      wx.hideLoading();
    });
  }
});

